package cn.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterPostProcessor;
import cn.wx.properties.MaProperties;
import cn.wx.properties.WxMaProperties;
import lombok.AllArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 微信公众平台注册,使用配置文件的方式
 *
 * @author: sunshaoping
 * @date: Create by in 5:11 下午 2020/5/25
 */
@Order(11)
@AllArgsConstructor
public class WxMaServiceRegisterPostProcessor implements WxServiceRegisterPostProcessor {

    private final WxMaProperties properties;

    private final WxMaConfigFactory<MaProperties> wxMaConfigFactory;

    @Override
    public void processor(WxServiceRegister wxServiceRegister) {
        //默认服务
        properties.verification(WxMaProperties.PREFIX);
        final WxMaService wxMaService = createWxMaService(properties);
        //注册默认bean
        wxServiceRegister.register(properties.getName(), wxMaService);

        List<MaProperties> multiple = properties.getMultiple();
        if (CollectionUtils.isEmpty(multiple)) {
            return;
        }

        Set<String> set = new HashSet<>(multiple.size() + 1);
        set.add(properties.getName());
        for (int i = 0; i < multiple.size(); i++) {
            MaProperties maProperties = multiple.get(i);
            String name = maProperties.getName();
            String prefix = WxMaProperties.PREFIX + ".multiple[" + i + "]";
            maProperties.verification(prefix);
            WxMaService service = createWxMaService(maProperties);
            if (set.contains(name)) {
                throw new IllegalStateException(prefix + ".name=" + name + ",已存在 ");
            }
            set.add(name);
            //注册bean
            wxServiceRegister.register(name, service);
        }
    }

    private WxMaService createWxMaService(MaProperties properties) {
        final WxMaService service = new WxMaServiceImpl();
        service.setWxMaConfig(wxMaConfigFactory.create(properties));
        return service;
    }

}
